import { h, ref, watch, onMounted } from 'vue'
import { FileSearchOutlined } from '@ant-design/icons-vue'
import * as Icon from '@ant-design/icons-vue'
import useAppStore from '@/store/app'

const generateMenu = (data = []) => {
  return data.map((item) => {
    if (!item || item.isHide) return null
    const menu = {
      icon: item.menuIcon ? h(Icon[item.menuIcon]) : null,
      path: item.path,
      key: item.path,
      type: item.type,
      title: item.label,
      label: item.label
    }

    if (item.children && item.children.length > 0) {
      menu.children = generateMenu(item.children)
      // menu.popupOffset = menu.icon ? [32, 0] : [8, 0]
    }
    if (menu.type === '目录') {
      return menu.children?.length > 0 ? menu : null
    }
    return menu
  })
}

export default function () {
  const menus = ref([])
  const menuSubKeys = ref([])
  const appStore = useAppStore()
  const getMenu = () => {
    const isReport = appStore.CURRENT_ROUTE_NAME === '报表中心'
    const reportRoute = appStore.reportRoute?.map((item) => ({ ...item, icon: FileSearchOutlined }))
    const currentRouteData = appStore.ROUTER_AUTHORITY.find((item) => item.label === appStore.CURRENT_ROUTE_NAME)
    if (!currentRouteData || !currentRouteData.children || currentRouteData.children.length === 0) return
    menus.value = generateMenu(isReport ? reportRoute : currentRouteData.children)
  }
  watch(
    () => appStore.reportRoute,
    (val) => {
      val.length > 0 && getMenu()
    }
  )
  onMounted(() => getMenu())
  return { menus, menuSubKeys }
}
